
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { getAuthAxios } from '../lib/authAxios.js';
import { message } from 'antd';
import powerPriceList from '../lib/powerPrice.js';
import { GlobalVarListener, DOMObserver, FormDataCollector, IFrameHandler } from '../lib/components';

// 360客户视图-地址信息-核查校验
const RootComponent = () => {
  const myAxios = getAuthAxios();
  const [addressWarningObj, setAddressWarningObj] = useState(null);
  const [tabName, setTabName] = useState('客户信息查询');
  const [formData, setFormData] = useState({});

  useEffect(() => {
    window.setMyGlobalVar('warningDomIndexs', []);
    setAddressWarningObj(window.getMyGlobalVar('warningObj'));
  }, []);
  
  // 处理全局变量变化
  const handleGlobalVarChange = (value, key) => {
    if (key === 'activeTabName' && (value === '用电客户视图' || value === '客户360视图')) {
      // 不再需要调用getDomPolling，由IFrameHandler组件处理
    } else if (key === 'warningObj') {
      setAddressWarningObj(value);
    }
  };
  
  // 处理iframe准备就绪
  const handleIFrameReady = (iframeDoc, iframe) => {
    const tabsEls = iframeDoc.querySelector(".nav-scroll-wrap > div ");
    tabsEls && Array.from(tabsEls.children)[0].click();
    
    // 获取监听tabs,判断在哪个标签执行哪个逻辑
    if (!tabsEls) return;
    
    setTimeout(() => {
      // 使用DOMObserver组件监听标签变化
      const tabObserver = new MutationObserver(() => {
        console.log('监听标签变化');
        const btnDom = iframeDoc.querySelector('#app > div:nth-child(2) > div > div > div > div.tab-comt-root > div.jxm-tab-pagesOne > div:nth-child(2) > div > div.card-box > div > div:nth-child(1) > div.card-third-box_yx > div.sg-btnGrounp-right > div:nth-child(2) > button.el-button.el-button--primary.el-button--mini');
        btnSearch(btnDom, iframeDoc);
        
        setTimeout(() => {
          handleTabChange(tabsEls, iframeDoc);
        }, 1000);
      });
      
      tabObserver.observe(tabsEls, { attributes: true });
      
      // 初始处理一次标签
      handleTabChange(tabsEls, iframeDoc);
    }, 500);
    
    // 收集表单数据
    setTimeout(() => {
      collectFormData(iframeDoc);
    }, 1000);
    
    // 处理导航按钮
    const tabNav = iframeDoc.querySelector('#app > div.bread-wrap > .bread-root');
    if (tabNav && window.getMyGlobalVar('activeTabName') === '用电客户视图') {
      handleBtn(tabNav);
    }
  };
  
  // 处理标签变化
  const handleTabChange = (tabsEls, iframeDoc) => {
    for (let item of Array.from(tabsEls.children)) {
      if (item.classList.contains('active')) {
        const newTabName = item.textContent;
        setTabName(newTabName);
        
        if (newTabName === '计费信息') {
          isChargeStationUser() ? powerPriceListener(iframeDoc) : '';
        }
        if (newTabName === "计量信息") {
          checkJL(iframeDoc);
        }
        
        const tabNav = iframeDoc.querySelector('#app > div.bread-wrap > .bread-root');
        if (!tabNav) return;
        
        const addressBtn = tabNav.querySelector("#_address-btn-360");
        if (!addressBtn) return;
        
        addressBtn.style.display = newTabName === '用户信息' ? 'block' : 'none';
      }
    }
  };
  
  // 收集表单数据
  const collectFormData = (iframeDoc) => {
    const formItemList = iframeDoc.querySelectorAll('.el-form-item');
    let tempFormData = {};
    
    formItemList.forEach(item => {
      if (item.querySelector('input')) {
        tempFormData[item.children[0].textContent] = {
          value: item.querySelector('input').value,
          dom: item.querySelector('input')
        };
      }
    });
    
    if (Object.keys(tempFormData).length > 0) {
      setFormData(tempFormData);
    }
  };
  
  // 以下是原有的功能函数，保持不变
  const btnSearch = (btnDom, iframeDom) => {
    // 原有功能保持不变
  };
  
  const handleBtn = (tabNav) => {
    // 原有功能保持不变
  };
  
  const isChargeStationUser = () => {
    // 原有功能保持不变
    return true; // 临时返回值，实际应使用原有逻辑
  };
  
  const powerPriceListener = (iframeDom) => {
    // 原有功能保持不变
  };
  
  const checkJL = (iframeDom) => {
    // 原有功能保持不变
  };
  
  return (
    <>
      {/* 使用GlobalVarListener组件监听全局变量变化 */}
      <GlobalVarListener 
        onChange={handleGlobalVarChange} 
      />
      
      {/* 使用IFrameHandler组件处理iframe */}
      <IFrameHandler
        containerSelector=".main-container-view"
        onIFrameReady={handleIFrameReady}
        displayFilter="block"
        targetIndex={1}
      />
    </>
  );
};

const init = () => {
  const container = document.createElement('div');
  document.body.appendChild(container);
  const root = ReactDOM.createRoot(container);
  root.render(<RootComponent />);
};

init();